import React, { useEffect, useState, useRef } from "react";
import styles from "./index.style";
import {
  ActivityIndicator,
  FlatList,
  TouchableOpacity,
  View,
  Text,
} from "react-native";
import { useFriendsActions, useFriendsState } from "@/hooks/Friend/friend";
import { Avatar } from "@rneui/themed";
import "dayjs/locale/zh-cn";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import { FriendStatus } from "@/types/friend";
import { useStompClient } from "@/hooks/stomp/stomp-service";
import { useTheme } from "@/contexts/ThemeContext";
import { useAuth } from "@/contexts/AuthContext";

import { router } from "expo-router";
import {useUserProfileState} from "@/hooks/user/user-profile";
import {DEFAULT_AVATAR_URL} from "@/config/default-value";

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

function formatUserStatus(status: FriendStatus): string {
  switch (status) {
    case FriendStatus.ONLINE:
      return "在线";
    case FriendStatus.OFFLINE | FriendStatus.HIDDEN:
      return "离线";
    default:
      return "离线";
  }
}

export default function FriendList() {
  const { colors } = useTheme();
  const { isAuthenticated } = useAuth();
  const { friends, loading, error } = useFriendsState();
  const { fetchFriends, fetchFriendRequestsCount, fetchFriendInfo } =
    useFriendsActions();
  const { connected } = useStompClient();
  const {currentUser} = useUserProfileState();


  // 添加本地状态，用于跟踪组件内的加载状态
  const [localLoading, setLocalLoading] = useState(false); // 默认不加载
  const [hasAttemptedLoad, setHasAttemptedLoad] = useState(false);
  const isMounted = useRef(true);
  const initialLoadDone = useRef(false); // 跟踪是否已经完成了初始加载

  // 加载数据的函数
  const loadData = async (forceReload = false) => {
    // 添加真实的认证检查，防止未登录状态下的API请求
    if (!isAuthenticated) {
      return;
    }

    // 如果已经有数据且不是强制刷新，则不重新加载
    if (!forceReload && friends && friends.length > 0) {
      setLocalLoading(false);
      setHasAttemptedLoad(true);
      initialLoadDone.current = true;
      return;
    }

    try {
      setLocalLoading(true);
      await fetchFriends();
    } finally {
      if (isMounted.current) {
        setLocalLoading(false);
        setHasAttemptedLoad(true);
        initialLoadDone.current = true;
      }
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    if (isAuthenticated && connected) {
      loadData();
      fetchFriendRequestsCount();
    }

    return () => {
      isMounted.current = false;
    };
  }, [isAuthenticated,connected]); // 依赖于认证状态，当状态变化时重新运行

  // 如果正在加载且没有数据，显示加载指示器
  if ((loading || localLoading) && (!friends || friends.length === 0)) {
    return (
      <View style={styles.loading}>
        <ActivityIndicator size="large" />
      </View>
    );
  }

  // 如果有好友数据，无论是否有错误，都显示好友列表
  if (friends && friends.length > 0) {
    return (
      <FlatList
        data={friends}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => {
          const { nickname, remark, avatar } = item;
          const lastOnlineText = formatUserStatus(
            connected ? item.friendStatus : FriendStatus.OFFLINE
          );
          return (
            <TouchableOpacity
              onPress={async () => {
                await fetchFriendInfo(item.id);
                router.navigate("/friend/card");
              }}
              style={[
                styles.listItem,
                {
                  borderBottomColor: colors.border.divider,
                },
              ]}
            >
              <View style={styles.avatarWrapper}>
                <Avatar
                  rounded
                  size={50}
                  source={{ uri: avatar }}
                  containerStyle={styles.avatar}
                />
                <View
                  style={[
                    styles.statusDot,
                    {
                      backgroundColor:
                        item.friendStatus === FriendStatus.ONLINE && connected
                          ? "#34C759"
                          : "#C6C6C8",
                    },
                  ]}
                />
              </View>
              <View
                style={[
                  styles.infoContainer,
                  { backgroundColor: colors.card.background },
                ]}
              >
                <Text style={[styles.nickname, { color: colors.text.primary }]}>
                  {nickname}
                  {remark ? (
                    <Text style={styles.remark}>（{remark}）</Text>
                  ) : null}
                </Text>
                <View style={styles.onlineRow}>
                  <Text style={styles.leftText}>{lastOnlineText}</Text>
                  {(item.friendStatus !== FriendStatus.ONLINE || !connected) && (
                    <Text style={styles.rightText}>
                      {item.id != currentUser.id ? (
                          item.lastOnlineTime
                              ? "上次在线于" + dayjs(item.lastOnlineTime).fromNow()
                              : "从未在线过" ) : "连接中..."}
                    </Text>
                  )}
                </View>
              </View>
            </TouchableOpacity>
          );
        }}
      />
    );
  }

  // 如果已经尝试加载数据但没有数据，且有错误，显示错误视图
  if (hasAttemptedLoad && error) {
    return (
      <View style={styles.errorContainer}>
        <Text style={styles.errorText}>加载失败，请重试</Text>
        <TouchableOpacity
          style={styles.retryButton}
          onPress={() => loadData(true)}
        >
          <Text style={styles.retryText}>重试</Text>
        </TouchableOpacity>
      </View>
    );
  }

  // 如果已经尝试加载数据但没有数据，且没有错误，显示空状态
  if (hasAttemptedLoad) {
    return (
      <View style={styles.emptyContainer}>
        <Text style={styles.emptyText}>暂无好友</Text>
      </View>
    );
  }

  // 默认显示加载状态
  return (
    <View style={styles.loading}>
      <ActivityIndicator size="large" />
    </View>
  );
}
